package com.mhy.tvcontrol;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

public class BluetoothService {
    private static String BufferRead = "00";
    private  final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    public static String ReadMsg = "00";
    public static int MESSAGE_TOAST = 5;
    public static String TOAST = "toast";
    public static ConnectedThread connectedThread;
    private ConnectThread connectThread;
    private final BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();
    /* access modifiers changed from: private */
    public final Handler mHandler;

    public BluetoothService(Context context, Handler handler) {
        this.mHandler = handler;
    }
    /**
     * 初始化 通知渠道
     */
    private final String channel1 = "message";
    private final String channel2 = "notification";
    private final String channel3 = "subscribe";

    public void initNotficChannel(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager notifyManager = (NotificationManager)context.getSystemService(
                    Context.NOTIFICATION_SERVICE);
            // 第三个参数表示通知的重要程度，默认则只在通知栏闪烁一下
            NotificationChannel channel01 = new NotificationChannel(channel1, "消息",
                    NotificationManager.IMPORTANCE_HIGH);
            channel01.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
            channel01.enableLights(true);//如果使用中的设备支持通知灯，则说明此通知通道是否应显示灯
            channel01.setShowBadge(true);//是否显示角标
            // 注册通道，注册后除非卸载再安装否则不改变
            notifyManager.createNotificationChannel(channel01);

            NotificationChannel notificationChannel = new NotificationChannel(channel2, "通知",
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
            // 注册通道，注册后除非卸载再安装否则不改变
            notifyManager.createNotificationChannel(notificationChannel);

            NotificationChannel notification = new NotificationChannel(channel3, "订阅",
                    NotificationManager.IMPORTANCE_LOW);
            notification.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
            // 注册通道，注册后除非卸载再安装否则不改变
            notifyManager.createNotificationChannel(notification);
        }
    }

    /**
     * 前台服务
     */
    private void initForeground(Service context) {
        NotificationCompat.Builder builder = null;
        //设置service为前台服务，提高优先级
        if (Build.VERSION.SDK_INT < 18) {
            //Android4.3以下 ，隐藏Notification上的图标
            builder = new NotificationCompat.Builder(context);
        } else if (Build.VERSION.SDK_INT >= 18 && Build.VERSION.SDK_INT <= 25) {
            //Android4.3 - Android7.0，隐藏Notification上的图标
            builder = new NotificationCompat.Builder(context);
        } else if (Build.VERSION.SDK_INT >= 26) {
            //Android7.0以上app启动后通知栏会出现一条"正在运行"的通知
            builder = new NotificationCompat.Builder(context, channel1);
        }
        if (builder != null) {
            builder.setPriority(NotificationCompat.PRIORITY_MAX)//设置优先级
                    .setContentTitle("DLNA")
                    .setContentText("前台运行中")
                    .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setAutoCancel(false);
            context.startForeground(1000, builder.build());
        }
    }
    public void connect(BluetoothDevice device) {
        if (connectedThread != null) {
            connectedThread.cancel();
            connectedThread = null;
        }
        this.connectThread = new ConnectThread(device);
        this.connectThread.start();
    }

    public void cancelThread() {
        if (connectedThread != null) {
            connectedThread.cancel();
            connectedThread = null;
        }
    }

    class ConnectThread extends Thread {
        private final BluetoothDevice mmDevice;
        private final BluetoothSocket mmSocket;

        public ConnectThread(BluetoothDevice device) {
            BluetoothSocket tmp = null;
            this.mmDevice = device;
            try {
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
            } catch (IOException e) {
            }
            this.mmSocket = tmp;
        }

        @Override
        public void run() {
            System.out.println("ConnectThread线程启动");
            try {
                this.mmSocket.connect();
                System.out.println("mmSocket.connect()");
                Message msg = BluetoothService.this.mHandler.obtainMessage(MESSAGE_TOAST);
                Bundle bundle = new Bundle();
                bundle.putString(TOAST, "连接成功");
                msg.setData(bundle);
                BluetoothService.this.mHandler.sendMessage(msg);
                BluetoothService.connectedThread = new ConnectedThread(this.mmSocket);
                BluetoothService.connectedThread.start();
            } catch (IOException e) {
                try {
                    this.mmSocket.close();
                } catch (IOException e2) {
                }
            }
        }
    }

    public class ConnectedThread extends Thread {
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;
        private final BluetoothSocket mmSocket;

        public ConnectedThread(BluetoothSocket socket) {
            this.mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
            }
            this.mmInStream = tmpIn;
            this.mmOutStream = tmpOut;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    int read = this.mmInStream.read(new byte[1024]);
                } catch (IOException e) {
                    return;
                }
            }
        }

        public void write(byte[] bytes) {
            try {
                Log.e("send",new String(bytes));
                this.mmOutStream.write(bytes);
            } catch (IOException e) {
            }
        }

        public void cancel() {
            try {
                this.mmSocket.close();
            } catch (IOException e) {
            }
        }
    }
}
